function varargout = TLDataStoreMemoryDlg(action,varargin)

% TL_DATASTOREMEMORY_DLG manages the user interface for TargetLink Datastore Memory block
%
% SYNTAX dlgInfo = TLDatastorememoryDlg('GetDlgInfo');
%   gets dialog info of TargetLink Datastore Memory block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLDatastorememoryDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLDatastorememoryDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLDatastorememoryDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLDatastorememoryDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLDatastorememoryDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLDatastorememoryDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.13 $
% $Date: 2011/07/21 14:57:21MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action

    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Data Store Memory';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames = {
            'Variable';
            'Autoscaling';
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Variable'
                [sheetDims,ctrlPos] = FcnVariableCtrlPositions(commonGeom);
                
            case 'Autoscaling'
                excludedCtrls = {'logging', 'keepParameter'};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);
                
            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims,ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos', commonGeom, sheetDims, bCodeComment ,bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName,dlgdata.pageNames, 'exact');
        switch pageName
            case 'Variable'
                dlgdata = ...
                    FcnCreateVariablePage(pageNum, dlgfig, dlgdata);
                
            case 'Autoscaling'
                dlgdata = ...
                    TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName, dlgdata.pageNames, 'exact');

        switch pageName
            case 'Variable'
                [dlgdata, bModified] = ...
                    FcnManageVariablePage(pageNum, dlgfig, dlgdata, pageAction);

            case 'Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata, bModified] = ...
                    TLManageDocCtrls('callback', pageNum, dlgfig, dlgdata, pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig  = varargin{1};
        dlgdata = varargin{2};
        % output page
        pageNum = varargin{3};
        pageName = dlgdata.pageNames{pageNum};

        switch pageName
            case 'Variable'
                dlgdata = FcnUpdateOutputPage(dlgdata, dlgfig, pageNum);
                
            case 'Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);

end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation',dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnVariableCtrlPositions calculates positions for all controls on variable page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnVariableCtrlPositions(commonGeom)

excludedCtrls = {'inheritproperties', 'saturate'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

% variable name, initial condition controls
[dsNameEditSize, ...
    initialLabelSize, ...
    useDDValueCheckboxSize] = ds_get_uicontrol_sizes( ...
    commonGeom, ...
    {'Data store name',        'text'
     'Initial condition',      'text'
     'Use value of Data Dictionary variable',    'checkbox'});

% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + commonGeom.checkboxHeight ...
    + rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

% move column 5
col(5) = col(4) + initialLabelSize(1) + colDelta / 3;

% ddv checkbox
cy = commonGeom.frameBottomEdgeBuffer;
cx = col(5);
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

% data store name label
cy = cy + commonGeom.checkboxHeight + rowDelta;
cx = col(1);
ctrlPos.dsNameLabel = [cx cy dsNameEditSize];

% data store name edit
cx = cx + dsNameEditSize(1) + colDelta / 3;
w = ctrlPos.varEdit(1) + ctrlPos.varEdit(3) - cx;
ctrlPos.dsNameEdit = [cx cy w ctrlPos.varEdit(4)];

% initial condition label
cx = col(4);
ctrlPos.initialLabel = [cx cy initialLabelSize];

% initial condition edit field
cx = col(5);
ctrlPos.initialEdit = [cx cy ctrlPos.varEdit(3:4)];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) + ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateVariablePage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateVariablePage(pageNum,dlgfig,dlgdata)

dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;
ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
data     = dlgdata.data;
pageName = dlgdata.pageNames{pageNum};
% create addoptGroupbox which will contain further options
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Initial condition'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% data store name controls
Children.dsNameLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Data store name:', ...
    'Position',           ctrlPos.dsNameLabel);

Children.dsNameEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'String',             data.datastorename, ...
    'Position',           ctrlPos.dsNameEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''dsNameEdit'')',pageName));


% output initial value controls
Children.initialLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Initial condition:', ...
    'Position',           ctrlPos.initialLabel);

Children.initialEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'String',             data.output.initial, ...
    'Position',           ctrlPos.initialEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''initialEdit'')',pageName));

% ddv checkbox
Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''useDDValueCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageVariablePage manages control actions of variable page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageVariablePage(pageNum,dlgfig,dlgdata,action)

Children  = dlgdata.pageData{pageNum}.children;

switch action

    case 'initialEdit'
        initialstr  = get(Children.initialEdit, 'String');
        if ~isempty(initialstr)
            if strcmp(initialstr, 'ddv')
                if isempty(dlgdata.data.output.variable)
                    beep;
                else
                    dlgdata.data.output.initial = ['ddv(''', dlgdata.data.output.variable, ''')'];
                    dlgdata.data.output.useddvariablevalue = true;
                end
            else
                dlgdata.data.output.initial = initialstr;
            end
        else
            beep;
        end
        bModified = 1;

    case 'dsNameEdit'
        dsNameStr = tl_deblank(get(Children.dsNameEdit, 'String'), 2);
        bMatch = ds_regexp('[a-zA-Z]+[_a-zA-Z0-9]*',dsNameStr) & length(dsNameStr) <= 31;
        if ~bMatch
            beep;
        else
            dlgdata.data.datastorename = dsNameStr;
        end
        bModified = 1;
        
   case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.output.initial = ['ddv(''', dlgdata.data.output.variable, ''')'];
            dlgdata.data.output.useddvariablevalue = true;
        else
            dlgdata.data.output.useddvariablevalue = false;
        end
        bModified = true;

    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage', pageNum, dlgfig, dlgdata, action, 'output');

        [dlgdata,bModified2] = ...
            TLManageScalingCtrls('manage', pageNum, dlgfig, dlgdata, action, 'output');

        bModified = bModified1 || bModified2;
end % switch action


%--------------------------------------------------------------------------
% FcnUpdateOutputPage updates the controls of the output tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum)

Children = dlgdata.pageData{pageNum}.children;

% invoke standard update methods
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
[initialValue, constraint, bCompliant] = ...
        tl_get_param_constraints(dlgdata.data.output, dlgdata.extdata.output, 'initial');
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', constraint);
dlgdata.extdata.output.defaultwidth = dlgdata.data.output.width;

dsNameEditCtrlStatus = struct('enable', 'on', 'string', dlgdata.data.datastorename);

% initial value edit field status
initialEditCtrlStatus = struct('enable', 'on', 'string', dlgdata.data.output.initial);
if dlgdata.data.output.useddvariablevalue
    initialEditCtrlStatus.enable = 'inactive';
end
initialEditCtrlStatus.iserror = ~bCompliant;

% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.output.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.output.useddvariablevalue;

ctrlsList = {'dsNameEdit', 'initialEdit', 'useDDValueCheckbox'};
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of standard controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

% set status of limit controls
TLSetCtrlsStatus(dlgfig, Children, ctrlsList)
